#include <event2/event.h>
#include <event2/listener.h>
#include <string.h>
#ifndef _WIN32
#include <signal.h>
#endif
#include <iostream>


#define SPORT  5001
using namespace std;

void listen_cb(struct evconnlistener* e,evutil_socket_t s,struct sockaddr *a,int socklen,void *arg)
{
   cout <<"listen cb" << endl;
}

int main()
{
#ifdef  _WIN32
	//init socket lib
	WSADATA  wsa;
	WSAStartup(MAKEWORD(2,2),&wsa);
#else
	//ignore pipe signal,send data to closed socket
	if(signal(SIGPIPE,SIG_IGN) == SIG_ERR)
		return 1;
#endif
    std::cout << " test Server!\n";
    event_base *base = event_base_new();
    if(base)
    {
	    cout << "Event_base_new success!" << endl;
    }
    sockaddr_in sin;
    memset(&sin,0,sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(SPORT);
    //listen to port
    evconnlistener *ev = evconnlistener_new_bind(base,//libevent context
		    listen_cb,   //connect to callback
		    base,      //callback function  get parms
		    LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, // address reuse , evlistener listen close and clear 
		    10,                  //connect  queue , duiying listen function
		    (sockaddr*)&sin,
		    sizeof(sin)                     // adress and port binded
		    );
    //event dispatcher
    if(base)
    	event_base_dispatch(base);
    if(base)
    	evconnlistener_free(ev);
    if(base)
    	event_base_free(base);
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}
